package com.ruoyi.sales.service.impl;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.core.domain.entity.ZcStock;
import com.ruoyi.sales.mapper.ZcStockMapper;
import com.ruoyi.sales.service.IZcStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ZcStockServiceImpl implements IZcStockService {

    @Autowired
    private ZcStockMapper stockMapper;

    /**
     * 查询列表数据
     * @DataScope 通过拦截器的方式实现数据权限的过滤，从而保证用户只能访问其有权限访问的数据
     * @param stock
     * @return
     */
    @Override
    @DataScope(stockAlias = "s")
    public List<ZcStock> selectStockList(ZcStock stock) {
        return stockMapper.selectStockList(stock);
    }

    @Override
    public ZcStock selectStockById(Long stockId) {
        return stockMapper.selectStockById(stockId);
    }

    @Override
    public boolean checkStockNameUnique(ZcStock stock) {
        Long stockId = StringUtils.isNull(stock.getStockId()) ? -1L : stock.getStockId();
        ZcStock info = stockMapper.checkStockNameUnique(stock.getStockName(), stock.getParentId());
        if (StringUtils.isNotNull(info) && info.getStockId().longValue() != stockId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int insertStock(ZcStock stock) {
        ZcStock info = stockMapper.selectStockById(stock.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("原料品类停用，不允许新增");
        }
        stock.setAncestors(info.getAncestors() + "," + stock.getParentId());
        return stockMapper.insertStock(stock);
    }

    @Override
    public int selectNormalChildrenStockById(Long stockId) {

        return stockMapper.selectNormalChildrenStockById(stockId);
    }

    @Override
    public int updateStock(ZcStock stock) {
        ZcStock newParentStock = stockMapper.selectStockById(stock.getParentId());
        ZcStock oldDept = stockMapper.selectStockById(stock.getStockId());
        if (StringUtils.isNotNull(newParentStock) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentStock.getAncestors() + "," + newParentStock.getStockId();
            String oldAncestors = oldDept.getAncestors();
            stock.setAncestors(newAncestors);
            updateStockChildren(stock.getStockId(), newAncestors, oldAncestors);
        }
        int result = stockMapper.updateStock(stock);
        if (UserConstants.DEPT_NORMAL.equals(stock.getStatus()) && StringUtils.isNotEmpty(stock.getAncestors())
                && !StringUtils.equals("0", stock.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentStockStatusNormal(stock);
        }
        return result;
    }

    /**
     * 是否存在子节点
     *
     * @param stockId id
     * @return
     */
    @Override
    public boolean hasChildByStockId(Long stockId) {
        int result = stockMapper.hasChildByStockId(stockId);
        return result > 0;
    }

    @Override
    public int deleteStockById(Long stockId) {
        return stockMapper.deleteStockById(stockId);
    }

    @Override
    public List<TreeSelect> selectStockTreeList(ZcStock stock) {
        List<ZcStock> stocks = SpringUtils.getAopProxy(this).selectStockList(stock);
        return buildStockTreeSelect(stocks);
    }

    @Override
    public List<ZcStock> buildStockTree(List<ZcStock> stocks) {
        List<ZcStock> returnList = new ArrayList<ZcStock>();
        List<Long> tempList = stocks.stream().map(ZcStock::getStockId).collect(Collectors.toList());
        for (ZcStock stock : stocks)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(stock.getParentId()))
            {
                recursionFn(stocks, stock);
                returnList.add(stock);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = stocks;
        }
        return returnList;
    }

    private void recursionFn(List<ZcStock> list, ZcStock t) {
        // 得到子节点列表
        List<ZcStock> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ZcStock tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    //判断是否有子节点
    private boolean hasChild(List<ZcStock> list, ZcStock t) {
        return getChildList(list, t).size() > 0;
    }

    //得到子节点列表
    private List<ZcStock> getChildList(List<ZcStock> list, ZcStock t) {
        List<ZcStock> tlist = new ArrayList<ZcStock>();
        Iterator<ZcStock> it = list.iterator();
        while (it.hasNext())
        {
            ZcStock n = (ZcStock) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getStockId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    @Override
    public List<TreeSelect> buildStockTreeSelect(List<ZcStock> stocks) {
        List<ZcStock> stockTrees = buildStockTree(stocks);
        return stockTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public int updateStockStatus(ZcStock stock) {
        return stockMapper.updateStockStatus(stock);
    }


    /**
     * 修改父级状态
     * @param stock
     */
    private void updateParentStockStatusNormal(ZcStock stock) {
        String ancestors = stock.getAncestors();
        Long[] stockIds = Convert.toLongArray(ancestors);
        stockMapper.updateStockStatusNormal(stockIds);
    }

    /**
     * 修改子元素关系
     * @param stockId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    private void updateStockChildren(Long stockId, String newAncestors, String oldAncestors) {
        List<ZcStock> children = stockMapper.selectChildrenStockById(stockId);
        for (ZcStock child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            stockMapper.updateStockChildren(children);
        }
    }
}
